import NProgress from "nprogress";
import router, { asyncRoutes } from "@/router";
import "nprogress/nprogress.css";
import { getToken } from "@/utils/auth"; // 从 Cookie 中获取 Token
import setPageTitle from "@/utils/pageTitle";
import { usePermissionStoreHook } from "@/stores/modules/permission";

// 设置页面标签名
const permissionStore = usePermissionStoreHook();

// 白名单路由
const whiteList = ["/login"];

router.beforeEach((to, from, next) => {
  NProgress.start();
  document.title = setPageTitle(to.meta.title);
  permissionStore.setRoutes(asyncRoutes);

  const token = getToken();
  console.log(`%cTo: ${to.path},from: ${from.path}`, "color: red");
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" }); // 如果已登录，跳转首页
      NProgress.done();
    } else {
      permissionStore.generateRoutes();
      // TODO 在这里获取菜单、字典、权限、角色等信息
      next();
    }
  } else if (whiteList.indexOf(to.path) !== -1) {
    next();
  } else {
    next(`/login?redirect=${to.path}`);
    NProgress.done();
  }
});
router.afterEach(() => {
  NProgress.done();
});
